﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using TradeClient.Logic.Entity;
using TradeClient.Logic.TradeCore;

using WAF.DAO;
using WAF.EntityFramework;

namespace TradeClient.Views
{
    public partial class PolicyConfig : Form
    {
        public PolicyConfig()
        {
            InitializeComponent();
        }

        private void PolicyConfig_Load(object sender, EventArgs e)
        {
            comboBoxPolicy.DisplayMember = "Text";
            comboBoxPolicy.ValueMember   = "Value";

            Init();

            comboBoxPolicy.SelectedIndex = 0;
        }

        private void comboBoxPolicy_SelectedIndexChanged(object sender, EventArgs e)
        {
            string policy = ((ComboBoxPolicyItem)comboBoxPolicy.SelectedItem).Value;
            SelectAccount(policy);
            SelectCode(policy);
        }

        //保存账号更改操作
        private void treeViewAccount_AfterCheck(object sender, TreeViewEventArgs e)
        {
            //只处理鼠标单击的事件
            if (comboBoxPolicy.SelectedItem != null && e.Action == TreeViewAction.ByMouse)
            {
                string policy = ((ComboBoxPolicyItem)comboBoxPolicy.SelectedItem).Value;
                string market = MarketType.Futures.ToString();
                string account = e.Node.Name;

                if (e.Node.Checked)
                {
                    PolicyAccount policyAccount = new PolicyAccount();
                    policyAccount.Policy  = policy;
                    policyAccount.Market  = market;
                    policyAccount.Account = account;

                    EntityAction.Insert(policyAccount);
                }
                else
                {
                    WAF.DAO.DbParameters param = new DbParameters();
                    param.Add("@Policy", policy, DbType.String);
                    param.Add("@Market", market, DbType.String);
                    param.Add("@Account", account, DbType.String);

                    WAF.DAO.DbAccess.ExeNonQuery("DELETE FROM PolicyAccount WHERE Policy=@Policy AND Market=@Market AND Account=@Account", param);
                }
            }
        }

        //保存品种更改操作
        private void treeViewCode_AfterCheck(object sender, TreeViewEventArgs e)
        {
            //只处理鼠标单击的事件
            if (comboBoxPolicy.SelectedItem != null && e.Action == TreeViewAction.ByMouse && e.Node.Nodes.Count == 0)
            {
                string policy = ((ComboBoxPolicyItem)comboBoxPolicy.SelectedItem).Value;
                string market = MarketType.Futures.ToString();
                string code = e.Node.Name;

                if (e.Node.Checked)
                {
                    PolicyQuote policyQuote = new PolicyQuote();
                    policyQuote.Policy = policy;
                    policyQuote.Market = market;
                    policyQuote.Code = code;

                    EntityAction.Insert(policyQuote);
                }
                else
                {
                    WAF.DAO.DbParameters param = new DbParameters();
                    param.Add("@Policy", policy, DbType.String);
                    param.Add("@Market", market, DbType.String);
                    param.Add("@Code", code, DbType.String);

                    WAF.DAO.DbAccess.ExeNonQuery("DELETE FROM PolicyQuote WHERE Policy=@Policy AND Market=@Market AND Code=@Code", param);
                }
            }
        }

        /// <summary>
        /// 加载所需数据
        /// </summary>
        private void Init()
        {
            LoadPolicy();
            LoadAccount();
            LoadCode();
        }

        /// <summary>
        /// 选中指定策略所交易的账户
        /// </summary>
        /// <param name="policy">策略名称</param>
        private void SelectAccount(string policy)
        {
            //清除选择
            foreach (TreeNode node in treeViewAccount.Nodes)
            {
                node.Checked = false;
            }
            
            PolicyAccount[] policyAccounts = EntityAction.Select<PolicyAccount>("SELECT * FROM PolicyAccount WHERE Policy=@Policy", new WAF.DAO.DbParameters("@Policy", policy, DbType.String));

            foreach(PolicyAccount policyAccount in policyAccounts)
            {
                foreach (TreeNode node in treeViewAccount.Nodes)
                {
                    if (node.Name == policyAccount.Account)
                    {
                        node.Checked = true;
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// 选中指定策略所交易的品种
        /// </summary>
        /// <param name="policy">策略名称</param>
        private void SelectCode(string policy)
        {
            //清除选择
            foreach (TreeNode exchangeNode in treeViewCode.Nodes)
            {
                foreach (TreeNode productNode in exchangeNode.Nodes)
                {
                    foreach (TreeNode codeNode in productNode.Nodes)
                    {
                       codeNode.Checked = false;
                    }
                }
            }

            PolicyQuote[] policyQuotes = EntityAction.Select<PolicyQuote>("SELECT * FROM PolicyQuote WHERE Policy=@Policy", new WAF.DAO.DbParameters("@Policy", policy, DbType.String));

            foreach (PolicyQuote policyQuote in policyQuotes)
            {
                foreach (TreeNode exchangeNode in treeViewCode.Nodes)
                {
                    foreach (TreeNode productNode in exchangeNode.Nodes)
                    {
                        foreach (TreeNode codeNode in productNode.Nodes)
                        {
                            if (codeNode.Name == policyQuote.Code)
                            {
                                codeNode.Checked = true;
                                goto NextQuote;
                            }
                        }
                    }
                }

            NextQuote: ;
            }
        }

        /// <summary>
        /// 加载交易策略列表
        /// </summary>
        private void LoadPolicy()
        {
            ComboBoxPolicyItem TestItem = new ComboBoxPolicyItem();
            TestItem.Text  = Test.GetInstance().PolicyChineseName;
            TestItem.Value = Test.GetInstance().PolicyName;

            ComboBoxPolicyItem Test1Item = new ComboBoxPolicyItem();
            Test1Item.Text  = Test1.GetInstance().PolicyChineseName;
            Test1Item.Value = Test1.GetInstance().PolicyName;

            ComboBoxPolicyItem[] items = new ComboBoxPolicyItem[] { TestItem, Test1Item };
            comboBoxPolicy.Items.AddRange(items);
        }

        /// <summary>
        /// 加载账户列表
        /// </summary>
        private void LoadAccount()
        {
            TradeClient.Logic.Entity.CtpAccount[] accounts = EntityAction.Select<TradeClient.Logic.Entity.CtpAccount>("select * from CtpAccount");

            foreach (TradeClient.Logic.Entity.CtpAccount account in accounts)
            {
                TreeNode treeNode = new TreeNode();
                treeNode.Name = account.Account;
                treeNode.Text = account.Account;
                treeViewAccount.Nodes.Add(treeNode);
            }
        }

        /// <summary>
        /// 加载交易品种
        /// </summary>
        private void LoadCode()
        {
            CtpInstrument[] instruments = EntityAction.Select<CtpInstrument>("select * from CtpInstrument order by ProductID, InstrumentID");

            foreach (CtpInstrument instrument in instruments)
            {
                //具体合约
                TreeNode newCodeNode = new TreeNode();
                newCodeNode.Name = instrument.InstrumentID;
                newCodeNode.Text = instrument.InstrumentName;

                foreach (TreeNode exchangeNode in treeViewCode.Nodes)
                {
                    if (exchangeNode.Name == instrument.ExchangeID)
                    {
                        foreach (TreeNode productNode in exchangeNode.Nodes)
                        {
                            if (productNode.Name == instrument.ProductID)
                            {
                                productNode.Nodes.Add(newCodeNode);

                                goto NextInstrument;
                            }
                        }

                        //合约类别
                        TreeNode addProductNode = new TreeNode();
                        addProductNode.Name = instrument.ProductID;
                        addProductNode.Text = instrument.ProductID;
                        addProductNode.Nodes.Add(newCodeNode);
                        exchangeNode.Nodes.Add(addProductNode);

                        goto NextInstrument;
                    }
                }

                //合约类别
                TreeNode newProductNode = new TreeNode();
                newProductNode.Name = instrument.ProductID;
                newProductNode.Text = instrument.ProductID;
                newProductNode.Nodes.Add(newCodeNode);

                //新的交易所节点
                TreeNode newExchangeNode = new TreeNode();
                newExchangeNode.Name = instrument.ExchangeID;
                newExchangeNode.Text = instrument.ExchangeID;
                newExchangeNode.Nodes.Add(newProductNode);
                treeViewCode.Nodes.Add(newExchangeNode);

                NextInstrument: ;
            }
        }

        /// <summary>
        /// 策略下拉框项
        /// </summary>
        private class ComboBoxPolicyItem
        {
            /// <summary>
            /// 策略中文名
            /// </summary>
            public string Text { get; set; }

            /// <summary>
            /// 策略名
            /// </summary>
            public string Value { get; set; }
        }

    }
}
